import Post from '../model/Post'
import Links from '../model/Links'

class ContentController {
  constructor() { }
  async getPostList (ctx) {
    const body = ctx.query;

    // 测试数据
    // const post = new Post({
    //   title: 'this id test 1',
    //   content: 'test content 1',
    //   catalog: 'share',
    //   fav: 20,
    //   reads: 0,
    //   answer: 0,
    //   status: 0,
    //   isTop: 0,
    //   sort: 0,
    //   tags: [{
    //     name: '精华',
    //     class: ""
    //   }],
    //   created: '2019-10-23 12:10:45'
    // })

    // const pwt = await post.save()
    // console.log(pwt, 'pwt')

    const sort = body.sort ? body.sort : 'created'
    const page = body.page ? parseInt(body.page) : 0
    const limit = body.limit ? parseInt(body.limit) : 20
    const options = {}
    if (typeof body.catalog !== 'undefined' && body.catalog !== '') {
      options.catalog = body.catalog
    }
    if (typeof body.isTop !== 'undefined') {
      options.isTop = body.isTop
    }
    if (typeof body.status !== 'undefined' && body.status !== '') {
      options.status = body.status
    }
    // if (typeof body.isEnd !== 'undefined') {
    //   options.isEnd = body.isEnd
    // }
    if (typeof body.tag !== 'undefined' && body.tag !== '') {
      options.tags = { $elemMatch: { name: body.tag } }
    }
    const result = await Post.getList(options, sort, page, limit)

    ctx.body = {
      code: 200, 
      data: result,
      mag: '获取文章列表数据成功!!!'
    }
  }

  // 友链
  async getLink(ctx) {
    const result = await Links.find({type: 'link'})
    ctx.body = {
      code: 200,
      data: result,
      msg: ''
    }
  }

  // 温馨提醒
  async getTips(ctx) {
    const result = await Links.find({type: 'tips'})
    ctx.body = {
      code: 200,
      data: result,
      msg: ''
    }
  }

  // 本周热议
  async getTopWeek(ctx) {
    const result = await Post.getTopWeek()
    ctx.body = {
      code: 200,
      data: result,
      msg: ''
    }
  }
}

export default new ContentController()
